﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Kinect.Audio;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;
using System.IO;

namespace KinectAssistant
{
    class BlackboardMotionDetector : MotionDetector
    {
        private const string RecognizerId = "SR_MS_en-US_Kinect_10.0";
        
        private string recognizeCommand = null;
        private KinectAudioSource source = null;
        private SpeechRecognitionEngine sre = null;
        private RecognizerInfo ri = null;

        public event EventHandler RecognizeCommandChanged;
        public string RecognizeCommand
        {
            get { return recognizeCommand; }
            set 
            {
                if (recognizeCommand != value)
                {
                    recognizeCommand = value;
                    if (RecognizeCommandChanged != null)
                    {
                        RecognizeCommandChanged(this, new EventArgs());
                    }
                }
            }
        }

        // Constructor
        public BlackboardMotionDetector()
        {
            
        }

        //to do
        public void Process()
        {

        }

        private void InitializeSpeech()
        {
            source = new KinectAudioSource();
            source.FeatureMode = true;
            source.AutomaticGainControl = false;
            source.SystemMode = SystemMode.OptibeamArrayOnly;

            ri = SpeechRecognitionEngine.InstalledRecognizers().Where(r => r.Id == RecognizerId).FirstOrDefault();
            if( ri==null )
            {
                System.Windows.Forms.MessageBox.Show("Could not find speech recognizer: " + RecognizerId + "Please refer to the sample requirements."); 
                return;
            }

            sre=new SpeechRecognitionEngine(ri.Id);
            var colors = new Choices();
            colors.Add("red");
            colors.Add("green");
            colors.Add("blue");
            colors.Add("black");
            var gb = new GrammarBuilder();
            gb.Culture = ri.Culture;
            gb.Append(colors);
            var g = new Grammar(gb);

            sre.LoadGrammar(g);
            sre.SpeechRecognized += SreSpeechRecognized;

            using (Stream s = source.Start())
            {
                sre.SetInputToAudioStream(s,new SpeechAudioFormatInfo(EncodingFormat.Pcm,16000,16,1,32000,2,null));
                sre.RecognizeAsync(RecognizeMode.Multiple);
            }
        }

        private void SreSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            recognizeCommand = e.Result.Text;
        }
    }
}
